﻿using AutoMapper;
using MD5Hash;
using MediatR;
using Microsoft.AspNetCore.Http;
using RBAC_Uthorization.API.Application.Command.UserComand;
using RBAC_Uthorization.API.DTO;
using RBAC_Uthorization.API.DTO.Request;
using RBAC_Uthorization.Domain;
using RBAC_Uthorization.Domain.Entity;
using RBAC_Uthorization.Infrstructre.Interface;
using Snowflake.Core;
using System.Diagnostics.CodeAnalysis;

namespace RBAC_Uthorization.API.Application.CommandHandlers.UserHandler
{
    public class UserinfoCreateCommandHandlers : IRequestHandler<UserInfoCreateCommand, ApiResult<int>>
    {
        private readonly IUserInfoRepository _userInfoRepository; 
        private readonly IOfficRepository _officRepository;
        private readonly ILogger<UserinfoCreateCommandHandlers> _logger;
        private readonly IMapper _mapper;
        private readonly IdWorker _idWorker;

        public UserinfoCreateCommandHandlers(IUserInfoRepository userInfoRepository, ILogger<UserinfoCreateCommandHandlers> logger, IOfficRepository officRepository, IMapper mapper, IdWorker idWorker)
        {
            _userInfoRepository = userInfoRepository;
            _logger = logger;
            _officRepository = officRepository;
            _mapper = mapper;
            _idWorker = idWorker;
        }

        public async Task<ApiResult<int>> Handle(UserInfoCreateCommand request, CancellationToken cancellationToken)
        {
            try
            {
               
                // 先查询公司是否存在
                var offic = await _officRepository.GetAllAsync();
               

                if (offic.Any(x => x.name == request.CreateDto.Offic_name))
                {
                    _logger.LogError($"公司名称已存在:{request.CreateDto.Offic_name}");
                    return new ApiResult<int>() { Code = ResultCode.Created, Message = "公司已存在" };
                }

                // 查询用户是否存在
                var user = await _userInfoRepository.GetAllAsync();
               

                if (user.Any(x => x.login_name == request.CreateDto.login_name))
                {
                    _logger.LogError($"用户已存在:{request.CreateDto.login_name}");
                    return new ApiResult<int>() { Code = ResultCode.Created, Message = "用户已存在" };
                }

                // 创建公司
                var officEntity = new sys_offic()
                {
                    //雪花算法
                    id = _idWorker.NextId().ToString(),
                    name = request.CreateDto.Offic_name,
                    end_date=request.CreateDto.end_date,
                    create_by = request.CreateName,
                    create_date = DateTime.UtcNow,
                    useable=request.CreateDto.useable,
                    sys_id = request.CreateDto.sys_id
                };
                await _officRepository.AddAsync(officEntity);
          

                // 创建用户使用AutoMapper
                var userEntity = _mapper.Map<sys_user>(request.CreateDto);

              
                userEntity.login_flag = request.CreateDto.useable;
                userEntity.password= request.CreateDto.password.GetMD5();
                userEntity.offic_id = officEntity.id;
                userEntity.create_by = request.CreateName;
                var entity=await _userInfoRepository.AddAsync(userEntity);
                //判断
                if (entity == null)
                {

                    _logger.LogError($"公司和用户创建失败，公司名称: {officEntity.name}, 用户ID: {userEntity.id},系统：{request.CreateDto.sys_id} ");
                    return new ApiResult<int>() { Code = ResultCode.Fail, Message = "创建失败" };
                }

                // 记录成功日志
                _logger.LogInformation($"系统：{request.CreateDto.sys_id} ，公司和用户创建成功，公司名称: {officEntity.name}, 用户ID: {userEntity.id}", officEntity.id, userEntity.id);

                return new ApiResult<int>() ;
            }
           
            catch (Exception ex)
            {
                _logger.LogError(ex, "公司跟用户创建处理请求时发生错误");
                return new ApiResult<int>() { Code = ResultCode.Fail, Message = "数据创建异常" };
            }
        }
    }
}
